package com.srwl.mytx.adapter;


import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.UserProfileActivity;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Donation;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.service.DonationService;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 个人收到的捐赠列表适配器
 */
public class PersonDonationRecordAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final String TAG = "PersonDonationRecordAda";
    private final List<Donation> donationList;
    private final Context context;
    private InteractionListener listener;
    private boolean bol_noData;//标记是否有数据
    private boolean bol_requestError;//标记是否有数据


    public PersonDonationRecordAdapter(Context context, List<Donation> donationList, InteractionListener listener) {
        this.donationList = donationList;
        this.context = context;
        this.listener = listener;
    }

    @Override
    public int getItemCount() {
        if (bol_noData || bol_requestError) {
            return 1;
        }
        return donationList.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (bol_noData) {
            return Constant.ITEM_TYPE_NO_DATA;
        } else if (bol_requestError) {
            return Constant.ITEM_TYPE_REQUEST_ERROR;
        }
        return Constant.ITEM_TYPE_NORMAL;

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == Constant.ITEM_TYPE_NO_DATA) {
            return new NoDataViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.no__data__layout, parent, false));
        } else if (viewType == Constant.ITEM_TYPE_REQUEST_ERROR) {
            return new RequestErrorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.request_error_layout, parent, false));
        }

        return new ReceivedDonationViewHolder(LayoutInflater.from(context).inflate(R.layout.layout_person_donation_record_item, parent, false));
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        int viewType = getItemViewType(position);
        if (viewType == Constant.ITEM_TYPE_NO_DATA) {
            NoDataViewHolder noDataViewHolder = (NoDataViewHolder) holder;
            noDataViewHolder.tv_tips.setText("没有捐赠记录");
        } else if (viewType == Constant.ITEM_TYPE_NORMAL) {
            ReceivedDonationViewHolder viewHolder = (ReceivedDonationViewHolder) holder;
            final Donation donation = donationList.get(position);
            User targetUser = donation.getTargetUser();
            if (targetUser != null) {
                viewHolder.iv_avatar.setVisibility(View.VISIBLE);
                viewHolder.tv_name.setVisibility(View.VISIBLE);
                // Glide.with(context).load(targetUser.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.drawable.tx_default_avatar).into(viewHolder.iv_avatar);
                GlideLoadUtils.glideLoad(context, targetUser.getAvatar(), viewHolder.iv_avatar, R.drawable.tx_default_avatar_1);
                viewHolder.tv_name.setText(targetUser.getUsername());
                viewHolder.tv_address.setText(targetUser.getArea());
            } else {
                viewHolder.iv_avatar.setVisibility(View.INVISIBLE);
                viewHolder.tv_name.setVisibility(View.INVISIBLE);
            }

            Integer type = donation.getType();
            if (type != null) {
                if (type == Constant.DONATION_TYPE_TO_PERSON || type == Constant.DONATION_TYPE_TO_EXPOSURE) {
                    viewHolder.tv_status.setText("[直捐]");
                } else {
                    viewHolder.tv_status.setText("[转赠]");
                }
            } else {
                Log.e(TAG, "onBindViewHolder: " + "捐赠类型为null:[" + donation.toString() + "]");
            }
            viewHolder.tv_extraMessage.setText(donation.getExtra());
            viewHolder.iv_avatar.setOnClickListener(v -> context.startActivity(new Intent(context, UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser)));
            viewHolder.tv_name.setOnClickListener(v -> context.startActivity(new Intent(context, UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser)));
            viewHolder.tv_amount.setText(Utils.moneyFormat(donation.getAmount()));
            viewHolder.tv_date.setText(DateUtils.getTimestampString(donation.getCreated()));
            if (!TextUtils.isEmpty(donation.getfId())) {

                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        listener.onItemViewClick(donation.getfId());
                    }
                });
            }

            viewHolder.tv_donationPraiseSize.setText(Utils.numberFormat(donation.getPraiseSize()));
            if (donation.getHasPraise() != null && donation.getHasPraise()) {
                viewHolder.iv_donationPraise.setImageResource(R.drawable.tx_good_red);

            } else {
                viewHolder.iv_donationPraise.setImageResource(R.drawable.tx_good_gray);
            }
            viewHolder.rl_praise.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (donation.getHasPraise()) {
                        removeDonationPraise(donation, viewHolder);
                    } else {
                        donationPraise(donation, viewHolder);
                    }
                }
            });

        }

    }

    private void donationPraise(Donation donation, ReceivedDonationViewHolder viewHolder) {

        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        Integer praiseSize = donation.getPraiseSize();
        if (praiseSize == null) {
            praiseSize = 0;
        }
        praiseSize++;
        donation.setPraiseSize(praiseSize);
        donation.setHasPraise(true);
        viewHolder.tv_donationPraiseSize.setText(Utils.numberFormat(praiseSize));
        viewHolder.iv_donationPraise.setImageResource(R.drawable.tx_good_red);
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .donationPraise(donation.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }

    private void removeDonationPraise(Donation donation, ReceivedDonationViewHolder viewHolder) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        Integer praiseSize = donation.getPraiseSize();
        if (praiseSize == null) {
            praiseSize = 1;
        }
        praiseSize--;
        donation.setPraiseSize(praiseSize);
        donation.setHasPraise(false);
        viewHolder.tv_donationPraiseSize.setText(Utils.numberFormat(praiseSize));
        viewHolder.iv_donationPraise.setImageResource(R.drawable.tx_good_gray);
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .removeDonationPraise(donation.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    class ReceivedDonationViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.iv_avatar)
        ImageView iv_avatar;
        @BindView(R.id.tv_nick)
        TextView tv_name;
        @BindView(R.id.tv_amount)
        TextView tv_amount;
        @BindView(R.id.tv_date)
        TextView tv_date;
        @BindView(R.id.tv_address)
        TextView tv_address;
        @BindView(R.id.tv_extra_message)
        TextView tv_extraMessage;
        @BindView(R.id.tv_status)
        TextView tv_status;
        @BindView(R.id.iv_donation_praise)
        ImageView iv_donationPraise;
        @BindView(R.id.tv_donation_praise_size)
        TextView tv_donationPraiseSize;
        @BindView(R.id.rl_praise)
        RelativeLayout rl_praise;

        public ReceivedDonationViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

        }
    }

    public interface InteractionListener {
        void onItemViewClick(String forwardId);

    }

    /**
     * 显示普通视图
     * 有数据的时候调用
     */
    public void showNormalView() {
        bol_noData = false;
        bol_requestError = false;
        notifyDataSetChanged();
    }

    /**
     * 显示无数据视图
     */
    public void showNoDataView() {
        bol_noData = true;
        notifyDataSetChanged();
    }

    /**
     * 显示请求数据错误视图
     */
    public void showErrorView() {
        bol_requestError = true;
        notifyDataSetChanged();
    }


}